
package com.mengmeizi;

import com.mengmeizi.db.DBHelper;
import com.mengmeizi.db.WallpaperDBBean;
import com.mengmeizi.services.ChangeWallpaperService;
import com.mengmeizi.util.Const;
import com.umeng.analytics.MobclickAgent;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.Toast;

import java.io.File;

public class ActSwitchWallpaper extends PreferenceActivity implements OnSharedPreferenceChangeListener,
        OnPreferenceClickListener {

    private SoftApplication application;

    private AlarmManager alarmManager;

    private PendingIntent pendingIntent;

    private SharedPreferences sharedPreferences;

    private CheckBoxPreference switcherPreference;

    private PreferenceCategory categoryPreference;

    private PreferenceScreen managerPreference;

    // private ListPreference listTimePreference;

    private Preference timeListPreference;

    // private boolean isShown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.act_switchwallpaper);

        application = (SoftApplication) getApplication();

        application.addActivity(this);

        // 获取perference对象
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);

        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, ChangeWallpaperService.class);
        pendingIntent = PendingIntent.getService(this, 0, intent, 0);

        // 开关设置页面的顶部title对象
        categoryPreference = (PreferenceCategory) getPreferenceScreen().findPreference("preTitle");
        // checkboxpreference对象
        switcherPreference = (CheckBoxPreference) getPreferenceScreen().findPreference("cbpWallpaperSwitcher");
        // 时间选择列表对象
        // listTimePreference = (ListPreference)
        // getPreferenceScreen().findPreference("lpfChangeTime");

        timeListPreference = (PreferenceScreen) getPreferenceScreen().findPreference("timeList");
        getChangeTime(sharedPreferences.getInt(Const.SELECTED_ITEM, 0));
        timeListPreference.setOnPreferenceClickListener(this);

        // 管理页面跳转对象
        managerPreference = (PreferenceScreen) getPreferenceScreen().findPreference("preManager");
        managerPreference.setOnPreferenceClickListener(this);
    }

    private boolean checkAndSetDB() {
        File file = new File(Const.FILENAME_DOWNLOAD);
        if (file.exists()) {
            File[] files = file.listFiles();
            int length = files.length;
            if (length >= 2) { // 下载目录下有图片
                DBHelper helper = new DBHelper(this, WallpaperDBBean.TABLE);
                helper.openReadableDatabase();
                Cursor cursor = helper.getDatas(WallpaperDBBean.sql$selectAll());
                if (cursor != null && cursor.getCount() == 0) { // 如果数据库里没有记录，进行扫描
                    helper.openWritableDatabase();

                    for (int i = 0; i < files.length; i++) {
                        WallpaperDBBean bean = new WallpaperDBBean();
                        bean.index = i;
                        bean.imageUrl = "";
                        bean.localPath = files[i].getAbsolutePath();
                        helper.insertItem(bean.conver2ContentValues());
                    }
                }
                helper.close();
                return true;
            } else {// 下载目录下没有图片
                return false;
            }
        } else {
            file.mkdirs();
            return false;
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("cbpWallpaperSwitcher")) {
            Boolean switchOn = sharedPreferences.getBoolean("cbpWallpaperSwitcher", false);
            if (checkAndSetDB()) {
                if (switchOn) {
                    // 获得时间间隔
                    long baseTime = getChangeTime(this.sharedPreferences.getInt(Const.SELECTED_ITEM, 0));
                    alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + baseTime, baseTime,
                            pendingIntent);
                    MobclickAgent.onEvent(this, "switchOn");
                } else {
                    alarmManager.cancel(pendingIntent);
                    MobclickAgent.onEvent(this, "switchOff");
                }
            } else {
                switcherPreference.setChecked(false);
                Toast.makeText(ActSwitchWallpaper.this, getString(R.string.noSaveImage), Toast.LENGTH_SHORT).show();
                categoryPreference.setTitle(getString(R.string.autoSwitchFail));
            }
        }
    }

    /***
     * 获取自动切换壁纸的时间间隔
     * 
     * @return
     */
    private long getChangeTime(int selected) {
        long interval = -1l;
        String sumery = "";
        if (selected > 4) {
            // 自定义时间
            interval = selected;
            sumery = sharedPreferences.getString("hour", "") + "小时" + sharedPreferences.getString("minute", "") + "分钟";
        } else {
            if (selected == 0) {
                interval = 15 * 60 * 1000; // 15分钟
                // interval = 15 * 1000; // 15秒
                sumery = "15分钟";
            } else if (selected == 1) {
                interval = 45 * 60 * 1000; // 45分钟
                // interval = 45 * 1000; // 45秒
                sumery = "45分钟";
            } else if (selected == 2) {
                interval = 60 * 60 * 1000;// 1小时
                sumery = "1小时";
            } else if (selected == 3) {
                interval = 2 * 60 * 60 * 1000;// 2小时
                sumery = "2小时";
            } else if (selected == 4) {
                interval = 3 * 60 * 60 * 1000; // 3小时
                sumery = "3小时";
            }
        }
        timeListPreference.setSummary(sumery);
        return interval;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(ActSwitchWallpaper.this, ActMore.class);
            ActSwitchWallpaper.this.startActivity(intent);
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        if (preference == timeListPreference) {
            int selectedTime = sharedPreferences.getInt(Const.SELECTED_ITEM, 0);
            Intent intent = new Intent(ActSwitchWallpaper.this, ActSwitchWallpaperTimeList.class);
            intent.putExtra(Const.SELECTED_ITEM, selectedTime);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else if (preference == managerPreference) {
            Intent intent = new Intent(ActSwitchWallpaper.this, ActManager.class);
            ActSwitchWallpaper.this.startActivity(intent);
            ActSwitchWallpaper.this.finish();
        }
        return false;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        // 获得返回结果
        int result = intent.getIntExtra(Const.SELECTED_ITEM, 0);
        // 通过选择的结果设定时间
        long baseTime = getChangeTime(result);
        alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + baseTime, baseTime, pendingIntent);
        // 保存选择的结果
        Editor editor = sharedPreferences.edit();
        editor.putInt(Const.SELECTED_ITEM, result);
        editor.commit();
    }
}
